import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AlipaySdk, AlipayFormData } from 'alipay-sdk';

/**
 * 支付宝支付服务
 */
@Injectable()
export class AlipayService {
  private alipaySdk: AlipaySdk;

  constructor(private readonly configService: ConfigService) {
    const alipayConfig = this.configService.get('payment.alipay');

    // 初始化支付宝SDK
    this.alipaySdk = new AlipaySdk({
      appId: alipayConfig.appId,
      privateKey: alipayConfig.privateKey,
      alipayPublicKey: alipayConfig.alipayPublicKey,
      gateway: alipayConfig.gateway,
      signType: 'RSA2',
    });
  }

  /**
   * 创建支付订单（PC网站支付）
   */
  async createPagePay(params: {
    outTradeNo: string; // 商户订单号
    totalAmount: number; // 订单金额
    subject: string; // 订单标题
    body?: string; // 订单描述
  }) {
    const alipayConfig = this.configService.get('payment.alipay');
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('returnUrl', alipayConfig.returnUrl);
    formData.addField('notifyUrl', alipayConfig.notifyUrl);
    formData.addField('bizContent', {
      outTradeNo: params.outTradeNo,
      productCode: 'FAST_INSTANT_TRADE_PAY',
      totalAmount: params.totalAmount.toFixed(2),
      subject: params.subject,
      body: params.body || params.subject,
    });

    // 生成支付链接
    const result = await this.alipaySdk.exec(
      'alipay.trade.page.pay',
      {},
      { formData },
    );

    return result;
  }

  /**
   * 创建支付订单（移动网站支付）
   */
  async createWapPay(params: {
    outTradeNo: string;
    totalAmount: number;
    subject: string;
    body?: string;
  }) {
    const alipayConfig = this.configService.get('payment.alipay');
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('returnUrl', alipayConfig.returnUrl);
    formData.addField('notifyUrl', alipayConfig.notifyUrl);
    formData.addField('bizContent', {
      outTradeNo: params.outTradeNo,
      productCode: 'QUICK_WAP_WAY',
      totalAmount: params.totalAmount.toFixed(2),
      subject: params.subject,
      body: params.body || params.subject,
    });

    const result = await this.alipaySdk.exec(
      'alipay.trade.wap.pay',
      {},
      { formData },
    );

    return result;
  }

  /**
   * 验证支付宝回调签名
   */
  verifyNotify(postData: any): boolean {
    return this.alipaySdk.checkNotifySign(postData);
  }

  /**
   * 查询订单
   */
  async queryOrder(outTradeNo: string) {
    const result = await this.alipaySdk.exec('alipay.trade.query', {
      bizContent: {
        outTradeNo,
      },
    });

    return result;
  }

  /**
   * 关闭订单
   */
  async closeOrder(outTradeNo: string) {
    const result = await this.alipaySdk.exec('alipay.trade.close', {
      bizContent: {
        outTradeNo,
      },
    });

    return result;
  }

  /**
   * 退款
   */
  async refund(params: {
    outTradeNo: string;
    refundAmount: number;
    refundReason?: string;
  }) {
    const result = await this.alipaySdk.exec('alipay.trade.refund', {
      bizContent: {
        outTradeNo: params.outTradeNo,
        refundAmount: params.refundAmount.toFixed(2),
        refundReason: params.refundReason || '用户申请退款',
      },
    });

    return result;
  }

  /**
   * 查询退款
   */
  async queryRefund(outTradeNo: string, outRequestNo: string) {
    const result = await this.alipaySdk.exec(
      'alipay.trade.fastpay.refund.query',
      {
        bizContent: {
          outTradeNo,
          outRequestNo,
        },
      },
    );

    return result;
  }
}
